﻿using Devil;
using UnityEngine;

namespace GameToolkit
{
    [DisallowMultipleComponent]
    public abstract class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
    {
        static T sInstance;
        public static T Instance
        {
            get { return sInstance; }
            private set
            {
                var inst = sInstance;
                sInstance = value;
                if (inst != null && inst != value)
                {
                    Debug.LogError($"There are more than one instance of <{typeof(T).Name}>");
                    inst.enabled = false;
                }
            }
        }

        public static T GetInstance()
        {
            if(sInstance == null && ParallelUnity.IsMainThread)
            {
                var go = new GameObject($"<{typeof(T).Name}>");
                sInstance = go.AddComponent<T>();
                GameObject.DontDestroyOnLoad(go);
            }
            return sInstance;
        }

        //protected readonly object _inner_lock = new object();

        protected virtual void OnEnable()
        {
            var inst = this as T;
            if(sInstance != null && sInstance != inst)
            {
                Debug.LogError($"There are more than one instance of <{typeof(T).Name}>");
                enabled = false;
            }
            else
            {
                sInstance = inst;
                Debug.Log($"Singleton<{typeof(T).Name}> was created.");
            }
        }

        protected virtual void OnDisable()
        {
            if (sInstance == this)
            {
                sInstance = null;
                Debug.Log($"Singleton<{typeof(T).Name}> was destroied.");
            }
        }
    }
}
